package com.ccsoft.leetcode.service;

import ch.qos.logback.core.joran.conditional.ElseAction;
import org.springframework.stereotype.Service;

/**
 * 14. 最长公共前缀，测试用例：
 * ["ab","a",""]
 * ["a"]
 * ["ab","a"]
 * ["flower","flow","flight"]
 * ["reflower","flower","flight"]
 * ["c","acc","ccc"]
 */
@Service
public class CommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        boolean flag = false;
        String commonPrefix = strs[0];
        if( "".equals(commonPrefix)) return "";
        if( strs.length == 1 ) flag = true;
        for(int i=1;i<strs.length;i++){
            String tmp = strs[i];
            if( "".equals(tmp)) return "";
            for(int j=0;j<tmp.length();j++){
                String substring = tmp.substring(0,tmp.length()-j);
                if( commonPrefix.indexOf(substring) == 0 ) {
                    commonPrefix = substring;
                    flag = true;
                    break;
                }
                flag = false;
            }
            if( !flag ) return "";
        }
        return flag ? commonPrefix : "";
    }
}
